<template>
  <el-card class="main-card">
    <div slot="header" class="card-header">
      <h2 class="card-header-title">叫号信息</h2>
    </div>

    <div class="calling-screen">
      <div class="calling-header">实时叫号</div>

      <!-- 滚动的叫号信息 -->
      <div class="calling-container" ref="scrollingContainer">
        <div class="calling-list" ref="scrollingContent">
          <div class="calling-item" v-for="(call, index) in displayedCallingData" :key="index">
            <div class="calling-info">
              <span class="info-label">患者：</span>
              <span class="info-value">{{ call.name }}</span>
            </div>
            <div class="calling-info">
              <span class="info-label">就诊科室：</span>
              <span class="info-value">{{ call.department }}</span>
            </div>
            <div class="calling-info">
              <span class="info-label">医生：</span>
              <span class="info-value">{{ call.doctor }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>


<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import request from '@/utils/request'

const scrollingContainer = ref(null)
const scrollingContent = ref(null)
const callingData = ref([])
const loading = ref(false)
let scrollInterval = null
let refreshInterval = null // 新增：用于存储定时器引用

// 计算属性：只显示前15条记录
const displayedCallingData = computed(() => {
  if (Array.isArray(callingData.value)) {
    return callingData.value.slice(0, 15)
  }
  return []
})

// 获取叫号信息
async function fetchCallingData() {
  loading.value = true
  try {
    const response = await request({
      url: '/system/today-reservation/list',
      method: 'get',
      timeout: 5000
    })

    // 核心修复：把 response.data.data → response.data（仅这一行改动）
    if (response && response.code === 200 && Array.isArray(response.data)) {
      callingData.value = response.data.map(item => ({
        department: item.department || '未知科室',
        doctor: item.doctor || '未知医生',
        name: item.name || '无名称'
      }))
    } else {
      console.warn('数据格式异常，加载模拟数据:', response)
      loadMockData()
    }
  } catch (err) {
    console.error('出诊数据获取失败，加载模拟数据：', err)
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
function loadMockData() {
  callingData.value = [
    { department: '内科', doctor: '张医生', name: '王小明', period: '上午' },
    { department: '外科', doctor: '李医生', name: '李小红', period: '下午' },
    { department: '儿科', doctor: '陈医生', name: '刘小军', period: '上午' },
    { department: '妇科', doctor: '赵医生', name: '孙小丽', period: '下午' },
    { department: '眼科', doctor: '周医生', name: '吴小刚', period: '上午' }
  ]
}

// 启动叫号信息滚动
function startScrolling() {
  nextTick(() => {
    const container = scrollingContainer.value
    const content = scrollingContent.value
    if (!container || !content) return

    // 只有当数据超过8条时才启动滚动
    if (displayedCallingData.value.length <= 8 && displayedCallingData.value.length > 0) {
      container.style.overflow = 'hidden'
      return
    }

    let scrollPosition = 0
    const scrollSpeed = 1
    const pauseTime = 3000

    const scroll = () => {
      const maxScroll = content.offsetHeight - container.offsetHeight
      if (maxScroll <= 0) return

      scrollPosition += scrollSpeed
      if (scrollPosition >= maxScroll) {
        scrollPosition = 0
        clearInterval(scrollInterval)
        setTimeout(() => {
          scrollInterval = setInterval(scroll, 50)
        }, pauseTime)
      }
      container.scrollTop = scrollPosition
    }
    scrollInterval = setInterval(scroll, 20)
  })
}

// 新增：启动定时刷新
function startAutoRefresh() {
  refreshInterval = setInterval(fetchCallingData, 5000)
}

onMounted(() => {
  fetchCallingData()
  startScrolling()
  startAutoRefresh() // 启动定时刷新
})

onUnmounted(() => {
  if (scrollInterval) clearInterval(scrollInterval)
  if (refreshInterval) clearInterval(refreshInterval) // 清理定时器
})

// 暴露方法给父组件使用
defineExpose({
  refresh: fetchCallingData
})
</script>

<style scoped lang="scss">
.main-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 6px;

  .card-header {
    background-color: #f7f8fa;
    border-bottom: 1px solid #e5e6eb;
    padding: 12px 20px;

    .card-header-title {
      font-size: 18px;
      font-weight: bold;
      color: #1f2d3d;
      margin: 0;
    }
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.calling-screen {
  .calling-header {
    background-color: #20a0ff;
    color: #fff;
    padding: 10px 15px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 4px 4px 0 0;
  }

  .calling-container {
    height: 400px;
    overflow: hidden;
    border: 1px solid #e5e6eb;
    border-top: none;
    border-radius: 0 0 4px 4px;
  }

  .calling-list {
    padding: 15px;
  }

  .calling-item {
    padding: 12px;
    border-bottom: 1px dashed #e5e6eb;
    &:last-child {
      border-bottom: none;
    }
  }

  .calling-info {
    margin-bottom: 8px;
    &:last-child {
      margin-bottom: 0;
    }

    .info-label {
      color: #666;
      font-size: 14px;
    }

    .info-value {
      color: #333;
      font-size: 14px;
      font-weight: 500;
    }
  }
}

:deep(.calling-container)::-webkit-scrollbar {
  width: 6px;
}

:deep(.calling-container)::-webkit-scrollbar-track {
  background: #f1f1f1;
}

:deep(.calling-container)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.calling-container)::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>